/*
 *  This file is part of Bracket Properties
 *  Copyright 2011 David R. Smith
 *
 */

package org.dave.bracket.properties;

/**
 * Default formatting for properties output. You can implement your own if you
 * don't like this one or it doesn't do what you require
 * 
 * @author Dave
 *
 */
public class BasicOutputFormat implements OutputFormat {
	
	final static String lineSeparator = System.getProperty("line.separator");
	
	/**
	 * Format the comments, key, separator, value(s), and line separator
	 * 
	 */
	public String format(String key, ValueModel model) {
		if(key == null) throw new RuntimeException("Key cannot be null in a format");
		StringBuffer buf = new StringBuffer();
		for(String c: model.getComments()){
			buf.append(c);
			buf.append(lineSeparator);
		}
	    StringBuilder keyBuilder=new StringBuilder();
	    for(int i=0;i<key.length();i++){
	    	char ch = key.charAt(i);
	    	if(ch==':'||ch=='='){
	    		keyBuilder.append('\\');	
	    	}
	    	keyBuilder.append(ch);
	    }
		buf.append(keyBuilder.toString());
		buf.append(model.getSeparator());
		int count =  model.getValues().size();
		int i = 0;
		for(String s: model.getValues()){
			buf.append(s);
			if(i<count-1) {
				buf.append('\\');
			}
			buf.append(lineSeparator);
			i++;
		}
		
		return buf.toString();
	}

	public String formatHeader() {
		StringBuffer buf = new StringBuffer("#;; Last generated on ");
		buf.append(new java.util.Date().toString());
		buf.append(lineSeparator);
		buf.append(lineSeparator);
		
		return buf.toString();
	}

	public String formatFooter() {
		StringBuffer buf = new StringBuffer(System.lineSeparator());
		buf.append("#;; end properties file ");
		buf.append(lineSeparator);
		return buf.toString();
	}

}
